package com.ylxn.config;

import com.ylxn.pojo.Configuration;
import com.ylxn.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 根据inputStream解析mapper.xml文件
     *
     * @param inputStream
     * @throws Exception
     */
    public void parse(InputStream inputStream) throws Exception {

        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();
        List<Element> list = new ArrayList<Element>();
        list.addAll(rootElement.selectNodes("//select"));
        list.addAll(rootElement.selectNodes("//insert"));
        list.addAll(rootElement.selectNodes("//update"));
        list.addAll(rootElement.selectNodes("//delete"));
        String namespace = rootElement.attributeValue("namespace");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
